/*
*
*  管理员数据模型
*  负责管理员部分数据
*
*/
// 导入数据文件
const db = require('../../config/db')
// 引入jwt token工具
const JwtUtil = require('../../utils/jwt')
// 引入处理加解密文件
// const aes = require('../../utils/aes')
const aes2 = require('../../utils/aes2')
// 引入全局文件
const config = require('../../config/default')

// 正则表达式
const rep_phone = /^1[3-9]\d{9}$/
const rep_email = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/

// 导出处理管理员数据的方法
module.exports = {
    // 编写管理员注册方法1
    // 参数：admin_id, admin_name, admin_password, admin_email, admin_create_time
    register(admin_id, admin_name, admin_password, admin_email, admin_create_time) {
        let admin_check_sql = 'select * from db_admin where admin_email="' + admin_email + '"';
        let pwd = aes2.aesEncrypt(admin_password)//加密
        let admin_insert_sql = 'insert into db_admin(admin_name,admin_password,admin_id,admin_email,admin_create_time) values("' + admin_name + '","' + pwd + '","' + admin_id + '","' + admin_email + '","' + admin_create_time + '")';
        return new Promise((resolve, reject) => {
            // 查询管理员表
            db.query(admin_check_sql, (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '查询管理员失败。',
                        err
                    })
                } else {
                    // 解构赋值(数据库)
                    if (rows.length != 0) {
                        resolve({
                            code: 201,
                            msg: '该管理员已存在。'
                        })
                    }
                    else {
                        // 添加管理员
                        db.query(admin_insert_sql, (err) => {
                            if (err) {
                                resolve({
                                    code: -1,
                                    msg: '注册管理员失败。'
                                })
                            } else {
                                resolve({
                                    code: 200,
                                    msg: '恭喜您,注册成功。',
                                    admin_name
                                })
                            }
                        })
                    }
                }
            })
        })
    },

    // 编写管理员注册方法2（邮箱验证）
    // 参数：admin_id, admin_name, admin_password, admin_email, admin_create_time, code
    addUser(admin_id, admin_name, admin_password, admin_email, admin_create_time, code) {
        let admin_check_sql = 'select * from db_admin where admin_email="' + admin_email + '"';
        let pwd = aes2.aesEncrypt(admin_password)//加密 如123123 加密后是 $2a$10$pt6AsnQ0fSuXY8ugsHSVbOvtRdEorr0j1MHjaEyAdCnEpH7aPseya
        let admin_insert_sql = 'insert into db_admin(admin_name,admin_password,admin_id,admin_email,admin_create_time) values("' + admin_name + '","' + pwd + '","' + admin_id + '","' + admin_email + '","' + admin_create_time + '")';
        return new Promise((resolve, reject) => {
            const addUser = () => {
                // 查询管理员表
                db.query(admin_check_sql, (err, rows) => {
                    if (err) {
                        resolve({
                            code: -1,
                            msg: '查询管理员失败。'
                        })
                    } else {
                        // 解构赋值(数据库)
                        if (rows.length != 0) {
                            resolve({
                                code: 201,
                                msg: '该管理员已存在。'
                            })
                        }
                        else {
                            // 添加管理员
                            db.query(admin_insert_sql, (err) => {
                                if (err) {
                                    resolve({
                                        code: -1,
                                        msg: '注册管理员失败。'
                                    })
                                } else {
                                    resolve({
                                        code: 200,
                                        msg: '恭喜您,注册成功。'
                                    })
                                }
                            })
                        }
                    }
                })
            }
            if (code) {
                let code_check_sql = 'select * from db_code where v1 = "' + code + '"'
                db.query(code_check_sql, (err, rows) => {
                    if (err) {
                        resolve({
                            code: 400,
                            msg: '验证码不存在。'
                        })
                    } else {
                        if (rows.length != 0) {
                            // 判断验证码是否冲突
                            let arr = [...rows].filter(item => {
                                if (item.v1 == code) {
                                    return item;
                                }
                            })
                            if (arr.length == 1) {
                                let sql = 'select * from db_code where v1 = "' + code + '" and code_id = "' + arr[0].code_id + '"';
                                db.query(sql, (err, rows) => {
                                    if (err) {
                                        resolve({
                                            code: -1,
                                            msg: '邮箱验证失败。'
                                        })
                                    } else {
                                        // 验证通过 , 再注册
                                        addUser();
                                    }
                                })
                            } else {
                                resolve({
                                    code: -1,
                                    msg: '验证码冲突了，请重新发送。'
                                })
                            }
                        } else {
                            resolve({
                                code: -1,
                                msg: '验证码错误。'
                            })
                        }
                    }
                })
            } else {
                resolve({
                    code: 400,
                    msg: '请发送邮箱验证码。'
                })
            }
        })
    },

    // 编写管理员登录方法
    // 参数：admin_account, admin_password
    login(admin_account, admin_password) {
        // console.log({admin_account,admin_password})
        return new Promise((resolve, reject) => {
            // 查询管理员表sql语句
            let admin_check_sql = ''
            // 判断管理员输入的是邮箱还是手机
            if (rep_email.test(admin_account)) {
                admin_check_sql = 'select * from db_admin where admin_email="' + admin_account + '"';
            }
            else
                if (rep_phone.test(admin_account)) {
                    admin_check_sql = 'select * from db_admin where admin_phone = "' + admin_account + '"';
                }
            db.query(admin_check_sql, (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '账号或密码错误0'
                    })
                } else {
                    if (rows.length == 1) {
                        // 匹配密码
                        if (aes2.aesDecrypt(admin_password, rows[0]['admin_password'])) {
                            let [{ admin_id, admin_name, admin_email, admin_phone, admin_avatar }] = rows
                            // 将管理员id传入并生成token
                            let jwt = new JwtUtil(admin_id)
                            // 获取token
                            let token = jwt.generateToken()
                            // 定义管理员对象
                            var user = {
                                code: 200,
                                msg: '恭喜您,登录成功。',
                                token,
                                admin_name,
                                admin_email,
                                admin_avatar
                            }
                            if (admin_phone) {
                                user['admin_phone'] = admin_phone
                            }
                            // 将 token 等信息反馈给客户端
                            resolve(user)
                        } else {
                            resolve({
                                code: -1,
                                msg: '账号或密码错误1'
                            })
                        }
                    } else {
                        resolve({
                            code: 500,
                            msg: '系统异常。'
                        })
                    }
                }
            })
        })
    },

    // 编写删除管理员方法(测试)
    // 参数：admin_id, code
    removexxx(admin_id, code) {
        return new Promise((resolve, reject) => {
            // 校验邮箱验证码
            db.query('select * from db_code where v1 = "' + code + '"', (err, rows) => {
                if (err) {
                    resolve({
                        code: 500,
                        msg: '服务端异常。'
                    })
                } else {
                    if (rows.length != 0) {
                        // 判断验证码是否冲突
                        let arr = [...rows].filter(item => {
                            if (item.v1 == code) {
                                return item;
                            }
                        })
                        if (arr.length == 1) {
                            db.query('select * from db_code where v1 = "' + code + '" and code_id = "' + arr[0].code_id + '"', (err, rows) => {
                                if (err) {
                                    resolve({
                                        code: -1,
                                        msg: '邮箱验证失败。'
                                    })
                                } else {
                                    // 验证通过 , 再删除
                                    db.query('delete from db_admin where admin_id = "' + admin_id + '"', function (err) {
                                        if (err) {
                                            resolve({
                                                code: -1,
                                                msg: '删除账号失败。'
                                            })
                                        } else {
                                            resolve({
                                                code: 200,
                                                msg: '删除账号成功。'
                                            })
                                        }
                                    })
                                }
                            })
                        } else {
                            resolve({
                                code: -1,
                                msg: '验证码冲突了，请重新发送。'
                            })
                        }
                    } else {
                        resolve({
                            code: -1,
                            msg: '验证码错误。'
                        })
                    }
                }
            })

        })
    },
    // 编写删除管理员方法
    remove(admin_id) {
        return new Promise((resolve, reject) => {
            db.query('delete from db_admin where admin_id = "' + admin_id + '"', function (err) {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '删除账号失败。'
                    })
                } else {
                    resolve({
                        code: 200,
                        msg: '删除账号成功。'
                    })
                }
            })
        })
    },
    // 编写修改密码方法
    // 参数：admin_id, new_password
    update(admin_id, new_password) {
        return new Promise((resolve, reject) => {
            let admin_check_sql = 'select * from db_admin where admin_id = "' + admin_id + '"'
            db.query(admin_check_sql, (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '查询管理员失败。'
                    })
                } else {
                    if (rows.length != 0) {
                        let pwd = aes2.aesEncrypt(new_password)
                        let admin_update_sql = 'update db_admin set admin_password = "' + pwd + '" where admin_id="' + admin_id + '"';
                        db.query(admin_update_sql, function (err) {
                            if (err) {
                                resolve({ code: -1, msg: "修改密码失败。" });
                            } else {
                                resolve({ code: 200, msg: "修改密码成功。" });
                            }
                        });
                    }

                }
            })
        })
    },
    // 编写修改头像方法
    // 参数：admin_id, avatar
    modify(admin_id, avatar) {
        return new Promise((resolve, reject) => {
            db.query("select * from db_admin where admin_id='" + admin_id + "'", (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '查询管理员失败。'
                    })
                } else {
                    if (rows.length != 0) {
                        db.query("update db_admin set admin_avatar = '" + avatar + "' where  admin_id = '" + admin_id + "'", function (err, rows) {
                            if (err) {
                                resolve({
                                    code: -1,
                                    msg: "修改头像失败。"
                                });
                            } else {
                                resolve({
                                    code: 200,
                                    msg: "修改头像成功。",
                                    avatar: image
                                })
                            }
                        })
                    }
                }
            })
        })
    },

    // 编写找回密码（邮箱验证）
    // 参数：admin_email, code, new_password
    findpwd(admin_email, code, new_password) {
        return new Promise((resolve, reject) => {
            const getpwd = () => {
                // 查询管理员表
                db.query('select * from db_admin where admin_email="' + admin_email + '"', (err, rows) => {
                    if (err) {
                        resolve({
                            code: -1,
                            msg: '查询管理员失败。'
                        })
                    } else {
                        // 解构赋值(数据库)
                        if (rows.length != 0) {
                            resolve({
                                code: 201,
                                msg: '该管理员已存在。'
                            })
                        }
                        else {
                            // 修改密码
                            let pwd = aes2.aesEncrypt(new_password)
                            let admin_update_sql = 'update db_admin set admin_password = "' + pwd + '" where admin_id="' + admin_id + '"';
                            db.query(admin_update_sql, function (err) {
                                if (err) {
                                    resolve({ code: -1, msg: "重置密码失败。" });
                                } else {
                                    resolve({ code: 200, msg: "重置密码成功。" });
                                }
                            });
                        }
                    }
                })
            }

            if (code) {
                let code_check_sql = 'select * from db_code where v1 = "' + code + '"'
                db.query(code_check_sql, (err, rows) => {
                    if (err) {
                        resolve({
                            code: 400,
                            msg: '验证码不存在。'
                        })
                    } else {
                        if (rows.length != 0) {
                            // 判断验证码是否冲突
                            let arr = [...rows].filter(item => {
                                if (item.v1 == code) {
                                    return item;
                                }
                            })
                            if (arr.length == 1) {
                                let sql = 'select * from db_code where v1 = "' + code + '" and code_id = "' + arr[0].code_id + '"';
                                db.query(sql, (err, rows) => {
                                    if (err) {
                                        resolve({
                                            code: -1,
                                            msg: '邮箱验证失败。'
                                        })
                                    } else {
                                        // 验证通过 , 重置密码
                                        getpwd();
                                    }
                                })
                            } else {
                                resolve({
                                    code: -1,
                                    msg: '验证码冲突了，请重新发送。'
                                })
                            }
                        } else {
                            resolve({
                                code: -1,
                                msg: '验证码错误。'
                            })
                        }
                    }
                })
            } else {
                resolve({
                    code: 400,
                    msg: '请发送邮箱验证码。'
                })
            }
        })
    },
    // 编写管理员分页列表方法
    // 参数：page_num,page_size
    items(page_num, page_size) {
        // console.log({page_num,page_size})
        return new Promise((resolve, reject) => {
            // const params = [(parseInt(page_num) - 1) * parseInt(page_size), parseInt(page_size)]
            let page_num2 = ((parseInt(page_num) - 1) * parseInt(page_size))
            let page_size2 = (parseInt(page_size))
            let sql = "select * from db_admin limit "+page_num2+","+page_size2+"";
            // console.log('--->',sql);
            db.query(sql, function (err, rows) {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '查询管理员失败。',
                        err
                    })
                } else {
                    //as更换名称
                    db.query('select count(*) as total from db_admin', function (error, among) {
                        if (error) {
                            resolve({
                                code: -1,
                                msg: '统计管理员数量失败。',
                                error
                            })
                        } else {
                            resolve({
                                code: 200,
                                msg: "获取分页列表成功。",
                                result: rows,
                                page: {
                                    page_num: page_num,
                                    page_size: page_size,
                                    total: among[0]['total'] //查询表中的数量
                                }
                            })
                        }
                    })
                }
            })

        })
    },
    // 编写获取昵称方法
    // 参数：admin_id
    nickName(admin_id) {
        return new Promise((resolve, reject) => {
            // 查询管理员
            db.query('select * from db_admin where admin_id="' + admin_id + '"', (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '查询昵称失败。'
                    })
                } else {
                    // console.log(rows)
                    resolve({
                        code: 200,
                        msg: '查询昵称成功',
                        title: "hello",
                        admin_name: rows[0] && rows[0]['admin_name']
                    })
                }
            })
        })
    },
    // 编写统计管理员人数方法
    all() {
        return new Promise((resolve, reject) => {
            db.query('select count(*) as total from db_admin', function (error, among) {
                if (error) {
                    resolve({
                        code: -1,
                        msg: '统计管理员数量失败。',
                        error
                    })
                } else {
                    resolve({
                        code: 200,
                        msg: "获取管理员总人数成功。",
                        total: among[0]['total']
                    })
                }
            })

        })
    },
}




